package net.lab1024.sa.base.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.common.lang.NonNullApi;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author: lijiajun
 * @date: 2024-10-23
 * @version: 1.0
 */
@NonNullApi
@RestControllerAdvice
public class UnifiedResponseAdvice implements ResponseBodyAdvice<Object> {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
//        return true;
        // TODO lijiajun 因为ResponseBodyAdvice会影响swagger,所以在这里需要过滤掉swagger
        return !returnType.getDeclaringClass().getName().contains("springdoc");
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 如果Controller直接返回String的话，SpringBoot是直接返回，故我们需要手动转换成json。
        if (body instanceof String) {
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return objectMapper.writeValueAsString(ResponseDTO.ok(body));
        }
        // 如果返回的结果是ResponseDTO对象，直接返回即可。
        if (body instanceof ResponseDTO) {
            return body;
        }
        // 如果是默认返回，则直接返回。
        return ResponseDTO.ok(body);
    }


//    @Override
//    @SneakyThrows
//    public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//        // 如果Controller直接返回String的话，SpringBoot是直接返回，故我们需要手动转换成json。
//        if (body instanceof String) {
//            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
//            return objectMapper.writeValueAsString(ResponseDTO.ok(body));
//        }
//        // 如果返回的结果是ResultData对象，直接返回即可。
//        if (body instanceof ResponseDTO) {
//            return body;
//        }
//        return ResponseDTO.ok(body);
//    }
}
